<template>
    <van-sticky>
        <van-nav-bar :title="title" left-text="返回" left-arrow @click-left="onClickLeft" />
    </van-sticky>
    <div v-if="loading">
        <CustomLoading :text="loadingText" />
    </div>
    <div v-else-if="hasZhuangXiangDetail">
        <div v-if="checkStatus('工长审批')" class="step-title">当前步骤（工长审批专项）</div>
        <div v-if="checkStatus('技管审批')" class="step-title">当前步骤（技管审批专项）</div>
        <div v-if="checkStatus('归档') && checkUser(['主任'])" class="step-title">当前步骤（主任知会专项）</div>
        <van-button v-if="checkStatus('归档') && checkUser(['主任'])" type="success" class="submit-button"
            @click="IKnow()">知会</van-button>
        <van-cell-group
            v-if="(checkStatus('工长审批') && checkUser(['工班长'])) || (checkStatus('技管审批') && checkUser(['技术管理']))"
            class="approval-input-group">
            <van-field v-model="approvalOpinion" label="审批意见" type="textarea" placeholder="请输入审批意见" rows="3" />
        </van-cell-group>
        <div class="approval-buttons" v-if="(
            (checkStatus('工长审批') && checkUser(['工班长'])) ||
            (checkStatus('技管审批') && checkUser(['技术管理']))
        )">
            <van-button type="success" class="approval-button" @click="handleAgree">同意</van-button>
            <van-button type="danger" class="approval-button" @click="handleReject">拒绝</van-button>
        </div>
        <div v-if="checkStatus('进行中')" class="step-title">
            <span>当前步骤（综合员分配作业人员）</span>
        </div>
        <van-cell-group v-if="checkStatus('进行中')">
            <van-cell title="任务列表" is-link @click="toRenWuList" />
        </van-cell-group>
        <div v-if="checkStatus('待下发')" class="step-title">当前步骤（工长分配牵头人）</div>
        <van-cell-group v-if="checkStatus('待下发') && (checkUser(['工班长']))">
            <van-field v-model="ZhuangXiangDetail.leader" label="牵头人" placeholder="点击搜索人员"
                @click="showUserSelector('负责人')" readonly />
        </van-cell-group>
        <van-button v-if="checkStatus('待下发') && (checkUser(['工班长']))" type="primary" class="submit-button"
            @click="submitLeader">提交</van-button>
        <div class="step-title">历史步骤</div>
        <van-cell-group v-if="!checkStatus(['待下发', '进行中'])">
            <van-cell title="任务列表" is-link @click="toRenWuList" />
        </van-cell-group>
        <van-cell-group v-if="!checkStatus('待下发')">
            <van-field :model-value="ZhuangXiangDetail.leaderName" label="牵头人" readonly />
        </van-cell-group>
        <UserSelector ref="userSelectorRef" @fillUser="fillUser" :noCheckbox="true" v-if="checkStatus('待下发')">
        </UserSelector>
        <van-cell-group inset>
            <van-cell title="专项附件" is-link @click="showFileList()" />
        </van-cell-group>
        <van-cell-group inset>
            <van-row>
                <van-col span="16" class="title-col">编号 {{ ZhuangXiangDetail.no }}</van-col>
                <van-col span="8" class="status-col">
                    <van-tag :color="getStatusColor(ZhuangXiangDetail.status)" round class="status-tag">
                        {{ ZhuangXiangDetail.status }}
                    </van-tag>
                </van-col>
            </van-row>
            <div class="content-div">
                <span class="bold-span">名称：</span>
                <span class="data-span">{{ ZhuangXiangDetail.name }}</span><br>
                <span class="bold-span">期限：</span>
                <span class="data-span">{{ ZhuangXiangDetail.period }}</span><br>
                <span class="bold-span">类型：</span>
                <span class="data-span">{{ ZhuangXiangDetail.type }}</span><br>
                <span class="bold-span">责任归属：</span>
                <span class="data-span">{{ ZhuangXiangDetail.responsible }}</span><br>
                <span class="bold-span">变电所：</span>
                <span class="data-span">{{ ZhuangXiangDetail.substations }}</span><br>
                <span class="bold-span">系统：</span>
                <span class="data-span">{{ ZhuangXiangDetail.system }}</span><br>
                <span class="bold-span">设备：</span>
                <span class="data-span">{{ ZhuangXiangDetail.equipments }}</span><br>
                <span class="bold-span">最小单元：</span>
                <span class="data-span">{{ ZhuangXiangDetail.unit }}</span><br>
                <span class="bold-span">要求：</span>
                <span class="data-span">{{ ZhuangXiangDetail.requirement.type }}</span><br></br>
                <span class="bold-span">描述：</span>
                <span class="remark-span">{{ ZhuangXiangDetail.remark }}</span><br>
            </div>
        </van-cell-group>
    </div>
    <FileList ref="FileListRef" :title="attachmentTitle" :attachments="attachmentData">
    </FileList>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import { showSuccessToast, showFailToast } from 'vant';
import CustomLoading from '@/components/CustomLoading.vue';
import UserSelector from '@/components/UserSelector.vue';
import FileList from '@/components/FileList.vue';
import { getStatusColor, convertDict, errorNotify } from '@/utils/Misc.js';
import zxlzAPI from '@/api/zxlz';
import { formatDeadline } from "@/utils/Format.js";
import { useRouter } from 'vue-router'
const router = useRouter();
import useStore from '@/store/index';
const store = useStore();
const title = ref("专项详情");
const ZhuangXiangDetail = ref({});
const userSelectorRef = ref(null);
const approvalOpinion = ref('');
const FileListRef = ref(null);
const attachmentTitle = ref("");
const attachmentData = ref([]);
const hasZhuangXiangDetail = ref(false);
const loading = ref(false);
const loadingText = ref('数据加载中...');
onMounted(() => {
    window.scrollTo(0, 0);
    getZhuangXiangDetail();
});
const checkUser = (targetRoles) => {
    const userRoles = store.user.roleNames || '';
    return targetRoles.some(role => userRoles.includes(role));
}
const IKnow = () => {
    loading.value = true;
    loadingText.value = '数据提交中...';
    const id = new URLSearchParams(window.location.search).get("id");
    zxlzAPI.todoApproval(id).then(res => {
        loading.value = false;
        showSuccessToast('已知会');
        router.back()
    }).catch((error) => {
        errorNotify("ZhuangXiangDetail.vue", "IKnow", error);
        loading.value = false;
    })
}
const toRenWuList = () => {
    router.push({
        path: '/ZhuangXiang/RenWu/list',
        query: {
            id: ZhuangXiangDetail.value.id
        }
    })
}
const checkStatus = (conditions) => {
    const currentStatus = ZhuangXiangDetail.value.status;
    if (Array.isArray(conditions)) {
        return conditions.includes(currentStatus);
    }
    return currentStatus === conditions;
}
const formatZhuangXiangDetail = (zxPlan) => {
    const {
        createdAt,
        startAt,
        endAt,
        status,
        type,
        responsibleName,
        substationNames,
        systemName,
        equipmentNames,
        requirement,
        unit,
        ...rest
    } = zxPlan;
    return {
        ...rest,
        no: `ZX${createdAt.split("-").join("").replace(" ", "").split(":").join("")}`,
        period: formatDeadline(startAt, endAt),
        status: convertDict("专项计划状态", "v2l", status),
        type: convertDict("专项计划类型", "v2l", type),
        responsible: responsibleName,
        substations: substationNames.replaceAll(",", "、"),
        system: systemName,
        equipments: equipmentNames.replaceAll(",", "、"),
        requirement: JSON.parse(requirement),
        unit: unit.replaceAll(",", "、"),
    };
};
const getZhuangXiangDetail = async () => {
    loading.value = true;
    loadingText.value = '数据加载中...';
    const id = new URLSearchParams(window.location.search).get("id");
    try {
        const res = await zxlzAPI.getPlanById(id);
        hasZhuangXiangDetail.value = true;
        ZhuangXiangDetail.value = formatZhuangXiangDetail(res.data.zxPlan);
    } catch (error) {
        errorNotify("ZhuangXiangDetail.vue", "getZhuangXiangDetail", error);
    } finally {
        loading.value = false;
    }
};
const showFileList = () => {
    attachmentTitle.value = "专项";
    attachmentData.value = ZhuangXiangDetail.value.planFileList;
    FileListRef.value.showFileList();
};
const showUserSelector = () => {
    userSelectorRef.value.showUserSelector();
};
const onClickLeft = () => {
    router.back();
};
const fillUser = (data) => {
    ZhuangXiangDetail.value.leader = data.name
    ZhuangXiangDetail.value.leaderId = data.id
};
const submitLeader = () => {
    const formData = {
        id: ZhuangXiangDetail.value.id,
        leaderId: ZhuangXiangDetail.value.leaderId
    };
    if (ZhuangXiangDetail.value.leaderId == null) {
        showFailToast('必填项不能\n为空');
        return;
    }
    showLoadingToast({
        message: '数据提交中...',
        forbidClick: true,
        duration: 0
    });
    zxlzAPI.setLeader(formData).then(res => {
        showSuccessToast('下发成功！');
        router.back()
    }).catch((error) => {
        errorNotify("ZhuangXiangDetail.vue", "submitLeader", error);
        closeToast();
    })
};
const handleAgree = () => {
    const id = new URLSearchParams(window.location.search).get('id');
    if (approvalOpinion.value === "") {
        approvalOpinion.value = "同意";
    }
    showLoadingToast({
        message: '数据提交中...',
        forbidClick: true,
        duration: 0
    });
    const approvalForm = {
        id: id,
        isApproval: true,
        remark: approvalOpinion.value
    };
    const currentStatus = ZhuangXiangDetail.value.status;
    const apiMethod = currentStatus === "工长审批"
        ? zxlzAPI.foremanApproval
        : zxlzAPI.supervisorApproval;
    apiMethod(approvalForm).then(res => {
        closeToast();
        showSuccessToast('审批成功！');
        router.back();
    }).catch((error) => {
        errorNotify("ZhuangXiangDetail.vue", "handleAgree", error);
        closeToast();
    });
};
const handleReject = () => {
    const id = new URLSearchParams(window.location.search).get('id');
    if (approvalOpinion.value === "") {
        showFailToast('审批意见不能为空！');
        return;
    }
    showLoadingToast({
        message: '数据提交中...',
        forbidClick: true,
        duration: 0
    });
    const approvalForm = {
        id: id,
        isApproval: false,
        remark: approvalOpinion.value
    };
    const currentStatus = ZhuangXiangDetail.value.status;
    const apiMethod = currentStatus === "工长审批"
        ? zxlzAPI.foremanApproval
        : zxlzAPI.supervisorApproval;
    apiMethod(approvalForm).then(res => {
        closeToast();
        showSuccessToast('审批成功！');
        router.back();
    }).catch((error) => {
        errorNotify("ZhuangXiangDetail.vue", "handleReject", error);
        closeToast();
    });
};
</script>
<style scoped>
.step-title {
    font-size: 16px;
    color: #333;
    margin: 1.2rem 0 0.8rem 1rem;
    padding-left: 0.75rem;
    border-left: 3px solid #1989fa;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
}

.step-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 3px;
    background: linear-gradient(to bottom, #1989fa, #40a9ff);
    border-radius: 3px;
}

.close-loop-btn {
    margin-right: 1rem;
}

:deep(.van-cell-group) {
    border: 1px solid #eee;
    margin: 0.5rem 1rem;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    background-color: #ffffff;
}

:deep(.van-cell-group:active) {
    transform: translateY(1px);
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
}

.title-col {
    font-weight: bold;
    padding-left: 1rem;
    padding-top: 1rem;
    margin-bottom: 0.5rem;
}

.status-col {
    padding-top: 1rem;
    padding-right: 1.2rem;
    text-align: right;
}

.status-tag {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 12px;
    font-weight: 500;
}

.content-div {
    padding-left: 1rem;
    padding-right: 1rem;
    padding-bottom: 1rem;
    line-height: 1.6;
}

.bold-span {
    font-weight: 600;
    display: inline-block;
    color: #555;
}

.data-span {
    color: #333;
    margin-bottom: 0.5rem;
    display: inline-block;
}

.remark-span {
    color: #333;
    margin: 0;
    text-align: justify;
    line-height: 1.6;
}

.approval-input-group {
    margin: 1rem 1rem 0.5rem;
}

.approval-buttons {
    display: flex;
    gap: 1rem;
    padding: 0 1rem;
    margin-bottom: 1rem;
    transition: all 0.3s ease;
}

.approval-button {
    flex: 1;
    height: 44px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.submit-button {
    margin: 0 1rem;
    width: calc(100% - 2rem);
    height: 44px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s ease;
}
</style>
